<?php

namespace addons\qingdongams\controller;

use addons\epay\library\Service;
use addons\qingdongams\model\PersonOrder;
use addons\qingdongams\model\Workorder;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

/**
 *发起支付
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class WebPay extends WebIndexApi
{

    protected $model = null;
    protected $noNeedLogin = ['*'];
    protected $log;

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 微信拉起支付
     */
    public function prepay($amount, $type = 'wechat', $method = 'miniapp', $out_trade_no = '', $openid = '')
    {

        //订单标题
        $title = '配件支付';

        //
        $notifyurl = config('service_url') . '/index/pay/notifyx/paytype/' . $type;
        $returnurl = config('service_url') . '/index/pay/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        $params = [
            'amount' => $amount,
            'orderid' => $out_trade_no,
            'type' => $type,
            'title' => $title,
            'notifyurl' => $notifyurl,
            'returnurl' => $returnurl,
            'method' => $method,
            'openid' => $openid,
        ];
        Log::write('支付发送' . json_encode($params), '', true);
        $response = Service::submitOrder($params);

        return $response;
    }

    /**
     * 支付成功，
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        Log::write('支付返回' . json_encode($paytype), '', true);
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        Log::write('支付返回' . json_encode($data), '', true);
        $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
        $out_trade_no = $data['out_trade_no'];
        $result1 = $result2 = false;
        $orderModel = new PersonOrder();
        $info = $orderModel->where(['order_sn' => $out_trade_no])->find();
        if (!$info) {
            Log::write('未找到订单号');
            echo "未找到订单";
            exit;
        }

        $data = [
            'customer_id' => $info['customer_id'] ?? '',
            'person_id' => $info['person_id'],
            'status' => 0,
            'process' => 0,
            'is_pause' => 0,
            'title' => '客户端购买备件工单',
            'workorder_number' => 'KQ' . date('Ymdhis') . rand(1000, 9999),
            'workorder_type' => '产品发货',
            'address' => $info['addrcity'],
            'address_detail' => $info['address'],
            'linkman' => $info['linkname'],
            'linkfun' => $info['linkmobile'],
            'appointment_time' => date("Y-m-d H:i:s"),
            'priority' => '一般',
            'desc' => $info['remark'],
            'parts' => $info['parts'],
            'use_parts' => $info['parts'],
            'pay_service' => $info['parts'],
            'total_money' => $info['amount'],
            'money' => $info['amount'],
            'is_pay' => 1,
            'pay_type' => $info['pay_type'],
            'pay_order' => $info['order_sn'],
            'pay_time' => $info['paytime'],
            'create_type' => 2,
        ];
        $error = '';
        Db::startTrans();
        try {
            //你可以在此编写订单逻辑

            $result1 = $orderModel->allowField(true)->isUpdate(true, ['order_sn' => $out_trade_no])->save([
                'pay_type' => $paytype,
                'status' => 1,
                'paytime' => time(),
            ]);
            $workModel = new Workorder();
            $result2 = $workModel->allowField(true)->save($data);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $error = '错误1';
        } catch (PDOException $e) {
            Db::rollback();
            $error = '错误2';
        } catch (Exception $e) {
            Db::rollback();
            $error = '错误3';
        }
        if ($result1 !== false || $result2 !== false) {
            return "表单失误";
        } else if (!$error) {
            return $error;
        }
        return $pay->success();
    }

    /**
     * 支付返回，
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }

}
